import { useState, useEffect, Fragment } from 'react';
import { connect } from 'umi';
import { Modal, Tag, Select, message, Spin, Checkbox, Input, Button } from 'antd';
import { ExportOutlined, BarsOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import './index.less'
import { debounce } from 'lodash';
import AddImg from '@/assets/add.png';

const { Option } = Select;

const CommonSelectOrg = (props: {
    dispatch?: any,
    title?: string, // 弹窗标题(选传)
    disabled?: boolean, // 设置disabled(选传)
    initList?: Array<{ shortName: string; id?: string; }>, // 初始列表（选传）
    initCanDelete?: boolean, // 设置初始值能否删除
    placeholder?: string, // 占位符（选传）
    multiple: boolean, // 单选：false   多选：true (必传)
    initOrgId?: string, // 初始的orgId，如果传了，那就根据这个初始orgId查询，否则就用maxOrgId查询（选传） 一般不用传
    isChooseVirtualGroup?: boolean, // 是否从虚拟小组选择，默认为false，传true表示可以从虚拟小组中选择
    mode?: string, // 选择组织的方式--样式 （btn）
    btnText?: string,//按钮文字
    onChange?: (checkedList: any[]) => void,
    onSuccessCallback?: (checkedList: any[]) => void, // 选择成功后的回调（选传）
    isCheck?: boolean, // 是否越权校验  true：需要校验   false: 跳过校验
    require?: boolean, // 点击确定校验选定内容是否为空数组  true：需要校验  false：不需要校验
}) => {
    const {
        dispatch,
        title = '发布单位', // 弹窗标题
        disabled = false, // 设置disabled(选传)
        initList = [], // 初始选中的列表（选传）
        initCanDelete = true, // 设置初始值能否删除  默认true：可以删
        placeholder = '请选择单位', // 占位符（选传）
        multiple = false, // 单选：false   多选：true
        initOrgId = '', // 初始的orgId，如果传了，那就根据这个初始orgId查询，否则就用maxOrgId查询（选传）
        isChooseVirtualGroup = false, // 是否从虚拟小组选择，默认为false，传true表示可以从虚拟小组中选择
        onChange,
        onSuccessCallback,
        isCheck = true,
        require = false,
        mode,
        btnText
    } = props;
    // 选择组织弹窗visible
    const [selectOrgVisible, setSelectOrgVisible] = useState<boolean>(false)
    // 单位搜索的value
    const [searchOrgName, setSearchOrgName] = useState<any>(null)
    // 单位搜索的list
    const [searchOrgList, setSearchOrgList] = useState<any[]>([])
    // 加载loading
    const [loading, setLoading] = useState<boolean>(false)
    // 面包屑list
    const [orgTabList, setOrgTabList] = useState<any[]>([])
    // 查询的结果列表
    const [orgList, setOrgList] = useState<any[]>([])
    // 选中的list
    const [checkedList, setCheckedList] = useState<any[]>([])
    // 最终选中的list
    const [finallList, setFinallList] = useState<any[]>([])
    // 展示单位内容
    const [isShowUnit, setIsShowUnit] = useState<boolean>(true)
    // 展示群组内容
    const [isShowGroup, setIsShowGroup] = useState<boolean>(false)
    // 群组加载loading
    const [groupLoading, setGroupLoading] = useState<boolean>(false)
    // 群组列表
    const [groupList, setGroupList] = useState<any[]>([])

    // 根据组织id获取当前组织
    const getCurrentOrgByOrgId = async (orgId: string = '', type: number) => {
        // orgId传空值，默认加载最大权限单位
        setLoading(true)
        await dispatch({
            type: 'commonSelectOrg/getOrgListByOrgId',
            payload: {
                orgId,
                type,
                check: isCheck
            },
            callback: (res: any) => {
                const { code, data, msg } = res;
                if (code === 1) {
                    const { upOrgList, subOrgList } = data;
                    let numIndex: number = 0;
                    if (upOrgList && upOrgList.length > 0) {
                        for (let i = 0; i < upOrgList.length; i++) {
                            if (upOrgList[i].id === initOrgId) {
                                numIndex = i
                                break
                            }
                        }
                    }
                    const handleUpOrgList = upOrgList.slice(numIndex);
                    setOrgTabList(handleUpOrgList);
                    setOrgList(subOrgList)
                } else {
                    message.error(msg)
                }
            }
        })
        setLoading(false)
    }
    // 获取虚拟小组
    const getVirtualGroup = async () => {
        setGroupLoading(true)
        await dispatch({
            type: 'commonSelectUser/getVirtualGroup',
            payload: {},
            callback: (res: any) => {
                const { code, data, msg } = res;
                if (code === 1) {
                    setGroupList(data)
                } else {
                    message.error(msg)
                }

            }
        })
        setGroupLoading(false)
    }

    useEffect(() => {
        if (initList !== finallList && initList.length > 0) {
            setCheckedList(initList);
            setFinallList(initList);
            onChange?.(initList);
        }
    }, [initList[0]?.id, initList.length]);

    useEffect(() => {
        if (selectOrgVisible) {
            setCheckedList(finallList)
            if (initOrgId) {
                getCurrentOrgByOrgId(initOrgId, 1)
            } else {
                getCurrentOrgByOrgId('', 1)
            }
            getVirtualGroup()
        }
    }, [selectOrgVisible]);

    // 展示弹窗
    const showModal = () => {
        setSelectOrgVisible(true)
    }

    // 取消
    const handleCancle = () => {
        setSelectOrgVisible(false)
    }

    // 确定
    const handleOk = () => {
        if (require && (!checkedList || checkedList.length === 0)) {
            message.error('请选择至少一个单位')
            return
        }
        onChange?.(checkedList);
        setCheckedList(checkedList);
        setFinallList(checkedList);
        setSelectOrgVisible(false)
        onSuccessCallback?.(checkedList)
    }

    // 删除某个单位
    const handleDelete = (id: string) => {
        const hasId = initList.findIndex((value) => value.id === id); // 初始的列表是否有该id的组织  > -1
        if (!initCanDelete && hasId > -1) {
            // 该组织无法修改
            message.error('该组织无法修改')
            return
        }
        const resultList: any = [];
        checkedList.map((item: any) => {
            if (item.id !== id) {
                resultList.push(item)
            }
        })
        setCheckedList(resultList)
    }

    // 输入时查询
    const handleSearch = debounce((value: any) => {
        setSearchOrgName(value || null)
        setSearchOrgList([])
        if (value) {
            dispatch({
                type: 'commonSelectOrg/getOrgListByName',
                payload: {
                    name: value
                },
                callback: (res: any) => {
                    const { code, data } = res;
                    if (code === 1) {
                        setSearchOrgList(data)
                    }
                }
            })
        }
    }, 200)

    // 失去焦点回调(清空)
    const handleBlur = () => {
        setSearchOrgList([])
        setSearchOrgName(null)
    }
    // 选择某个下拉回调
    const handleChange = (value: any) => {
        const stringToObject: any = JSON.parse(value); // 选中的object
        if (multiple) {
            // 如果是多选，则看这个id在不在checkedList里面，如果不在，则push
            const changeCheckedList: any[] = [...checkedList]
            const ids: any[] = checkedList.map((v) => {
                return v.id
            })
            if (ids.includes(stringToObject.id)) {
                message.info('该组织已被选中')
            } else {
                changeCheckedList.push({
                    id: stringToObject.id,
                    shortName: stringToObject.shortName
                })
                setCheckedList(changeCheckedList)
            }
        } else {
            // 单选，则替换
            const changeCheckedList: any[] = [
                {
                    id: stringToObject.id,
                    shortName: stringToObject.shortName
                }
            ]
            setCheckedList(changeCheckedList)
        }
        // 选择完毕后清空
        handleBlur()
    }

    // 选择checkBox（单选）
    const handleOnChangeCheck = (id: string, shortName: string, e: any) => {
        if (e.target.checked) {
            // 如果是选中
            if (multiple) {
                // 如果是多选，则push
                const changeCheckedList: any[] = [...checkedList]
                changeCheckedList.push({
                    id,
                    shortName
                })
                setCheckedList(changeCheckedList)
            } else {
                // 如果是单选，则替换
                const changeCheckedList: any[] = [
                    {
                        id,
                        shortName
                    }
                ]
                setCheckedList(changeCheckedList)
            }
        } else {
            // 取消选中，删除
            handleDelete(id)
        }
    }
    // checkBox是否选择（单选）
    const handleChecked = (id: string) => {
        let result: boolean = false;
        checkedList.map((item) => {
            if (item.id === id) {
                result = true
            }
        })
        return result
    }

    // 选择checkbox（单位全选）
    const onChangeAll = (e: any) => {
        const changeCheckedList: any[] = [...checkedList];
        if (e.target.checked) {
            orgList.map((item: any) => {
                const hasId = checkedList.findIndex((value) => value.id === item.id);
                if (hasId === -1) {
                    changeCheckedList.push(item);
                }

            })
        } else {
            orgList.map((item: any) => {
                if (changeCheckedList.length > 0) {
                    let t = 0;
                    for (let i = 0; i < changeCheckedList.length; i++) {
                        if (changeCheckedList[i].id === item.id) {
                            const hasId = initList.findIndex((value) => value.id === item.id); // 初始的列表是否有该id的组织  > -1
                            if (initCanDelete || hasId === -1) {
                                // 删除起始坐标为t的值
                                changeCheckedList.splice(t, 1);
                            }
                        }
                        t++;
                    }
                }
            })
        }
        setCheckedList(changeCheckedList)
    }
    // checkBox是否选择（单位全选）
    const handleCheckAll = () => {
        let result: boolean = true;
        orgList.map((item: any) => {
            const hasId = checkedList.findIndex((value) => value.id === item.id);
            if (hasId === -1) {
                result = false;
            }
        })
        return result
    }
    // 多选删除组织
    const handleMultipleDelete = (id: string) => {
        const hasId = initList.findIndex((value) => value.id === id); // 初始的列表是否有该id的人员  > -1
        if (!initCanDelete && hasId > -1) {
            // 该组织无法修改
            message.error('该组织无法修改')
            return
        }
        const resultList: any = [];
        checkedList.map((item: any) => {
            if (item.id !== id) {
                resultList.push(item)
            }
        })
        setCheckedList(resultList)
        setFinallList(resultList);
        onChange?.(resultList);
    }

    // 改变展示单位
    const handleChangeShowUnit = () => {
        setIsShowUnit(!isShowUnit)
    }
    // 改变展示群组
    const handleChangeShowGroup = () => {
        setIsShowGroup(!isShowGroup)
    }

    // 选择checkbox（群组全选）
    const onChangeGroupAll = (e: any) => {
        const changeCheckedList: any[] = [...checkedList];
        if (e.target.checked) {
            groupList.map((item: any) => {
                const hasId = checkedList.findIndex((value) => value.id === item.id);
                if (hasId === -1) {
                    changeCheckedList.push(item);
                }

            })
        } else {
            groupList.map((item: any) => {
                if (changeCheckedList.length > 0) {
                    let t = 0;
                    for (let i = 0; i < changeCheckedList.length; i++) {
                        if (changeCheckedList[i].id === item.id) {
                            const hasId = initList.findIndex((value) => value.id === item.id); // 初始的列表是否有该id的组织  > -1
                            if (initCanDelete || hasId === -1) {
                                // 删除起始坐标为t的值
                                changeCheckedList.splice(t, 1);
                            }
                        }
                        t++;
                    }
                }
            })
        }
        setCheckedList(changeCheckedList)
    }
    // checkBox是否选择（群组全选）
    const handleCheckGroupAll = () => {
        let result: boolean = true;
        groupList.map((item: any) => {
            const hasId = checkedList.findIndex((value) => value.id === item.id);
            if (hasId === -1) {
                result = false;
            }
        })
        return result
    }

    return (
        <Fragment>
            {
                !multiple &&
                <div className='disabledFieldPropsCom' onClick={!disabled ? showModal : () => { }}>
                    <Input
                        suffix={<ExportOutlined />}
                        value={finallList && finallList.length > 0 ? finallList[0].shortName : ''}
                        placeholder={placeholder || '请选择单位'}
                        allowClear={false}
                        disabled={disabled}
                    />
                </div>
            }
            {
                multiple && mode === 'btn' &&
                <Button
                    type="default"
                    onClick={() => {
                        setFinallList([])
                        showModal()
                    }}
                >
                    {btnText}
                </Button>
            }
            {
                multiple && !mode &&
                <div className='multipleOrgsWrap'>
                    {
                        finallList && finallList.length > 0 &&
                        finallList.map((item: any) => {
                            const hasId = initList.findIndex((value) => value.id === item.id); // 初始的列表是否有该id的人员  > -1
                            return (
                                <div key={`finall_item_${item.id}`} className="orgSelectDiv" onClick={() => {
                                    if (!disabled && (hasId === -1 || initCanDelete)) {
                                        handleMultipleDelete(item.id)
                                    }
                                }}>
                                    {item.shortName}
                                </div>
                            )
                        })
                    }
                    {
                        !disabled &&
                        <div className='addBtn' onClick={showModal}>
                            <img className="addImg" src={AddImg} alt="" />
                            <div className='userName'>添加单位</div>
                        </div>
                    }
                </div>
            }
            <Modal
                title={title}
                className="commonSelectOrg"
                destroyOnClose
                maskClosable={false}
                visible={selectOrgVisible}
                onOk={handleOk}
                onCancel={handleCancle}
                width={870}
            >
                <div className='selectOrgWrap'>
                    <div className='choose_left'>
                        {
                            checkedList && checkedList.length > 0 &&
                            checkedList.map((item: any) => {
                                const hasId = initList.findIndex((value) => value.id === item.id); // 初始的列表是否有该id的组织  > -1
                                return (
                                    <Tag closable={hasId === -1 || initCanDelete} onClose={() => { handleDelete(item.id) }} key={`checked_item_${item.id}`}>{item.shortName}</Tag>
                                )
                            })
                        }
                        <Select
                            dropdownClassName="searchOrgWrap"
                            showSearch={true}
                            placeholder="单位搜索"
                            value={searchOrgName}
                            showArrow={false}
                            filterOption={false}
                            onSearch={handleSearch}
                            onChange={handleChange}
                            notFoundContent={null}
                            dropdownMatchSelectWidth={false}
                            autoFocus={true}
                            bordered={false}
                            onBlur={handleBlur}
                        >
                            {
                                searchOrgList && searchOrgList.length > 0 &&
                                searchOrgList.map((item: any) => {
                                    const object2String = JSON.stringify(item);
                                    return (
                                        <Option key={`search_item_${item.id}`} value={object2String} style={{ width: '240px', left: '0px' }}>
                                            <div style={{ marginTop: '-2px' }}>{item.shortName}</div>
                                        </Option>

                                    )
                                })
                            }
                        </Select>
                    </div>
                    <div className='choose_right'>
                        <div className='org_common_wrap'>
                            <div className='org_common_top' onClick={handleChangeShowUnit}>
                                <div className='top_title'>从单位中选择</div>
                                <div className='top_icon'>{isShowUnit ? <UpOutlined /> : <DownOutlined />}</div>
                            </div>
                            {
                                isShowUnit &&
                                <div className='unit_con'>
                                    <div className='org_tabs'>
                                        {
                                            orgTabList && orgTabList.length > 0 &&
                                            orgTabList.map((item: any) => {
                                                return (
                                                    <div onClick={() => { getCurrentOrgByOrgId(item.id, 1) }} className='tab_item' key={`org_tab_${item.id}`}>
                                                        {item.shortName}
                                                    </div>
                                                )
                                            })
                                        }
                                    </div>
                                    <div className='org_list'>
                                        <Spin size="large" spinning={loading}>
                                            {
                                                multiple &&
                                                <div className='org_item'>
                                                    <Checkbox onChange={(e) => { onChangeAll(e) }} checked={handleCheckAll()}>
                                                        全选
                                                    </Checkbox>
                                                </div>
                                            }
                                            {
                                                orgList && orgList.length > 0 &&
                                                orgList.map((item: any) => {
                                                    return (
                                                        <div className='org_item' key={`org_item_${item.id}`}>
                                                            <Checkbox onChange={(e) => { handleOnChangeCheck(item.id, item.shortName, e) }} checked={handleChecked(item.id)}>
                                                                {item.shortName} ({item.userCount}人)
                                                            </Checkbox>
                                                            {
                                                                item.orgCount > 0 &&
                                                                <div className='choose_next' onClick={() => { getCurrentOrgByOrgId(item.id, 0) }}>
                                                                    <BarsOutlined />&nbsp;&nbsp;下级
                                                                </div>
                                                            }
                                                        </div>
                                                    )
                                                })
                                            }
                                        </Spin>
                                    </div>
                                </div>
                            }
                        </div>

                        {
                            isChooseVirtualGroup &&
                            <div className='org_common_wrap'>
                                <div className='org_common_top' onClick={handleChangeShowGroup}>
                                    <div className='top_title'>从我的群组中选择</div>
                                    <div className='top_icon'><span className='groupCount'>{groupList.length}个小组</span>{isShowGroup ? <UpOutlined /> : <DownOutlined />}</div>
                                </div>
                                <Spin size="large" spinning={groupLoading}>
                                    {
                                        isShowGroup && multiple &&
                                        <div className='group_con'>
                                            <Checkbox onChange={(e) => { onChangeGroupAll(e) }} checked={handleCheckGroupAll()}>
                                                全选
                                            </Checkbox>
                                        </div>
                                    }
                                    {
                                        isShowGroup && groupList && groupList.length > 0 &&
                                        groupList.map((item: any) => {
                                            return (
                                                <div className='group_con' key={`group_item_${item.id}`}>
                                                    <Checkbox onChange={(e) => { handleOnChangeCheck(item.id, item.shortName, e) }} checked={handleChecked(item.id)}>
                                                        <div className='grop_item'>
                                                            <div className='group_name'>{item.shortName}（{item.userCount}人）</div>
                                                        </div>
                                                    </Checkbox>
                                                </div>
                                            )
                                        })
                                    }
                                </Spin>
                            </div>
                        }

                    </div>
                </div>
            </Modal>
        </Fragment>
    )

}
export default connect()(CommonSelectOrg);